package io.focus.mijin.zuul.ratelimit.config;

import io.focus.mijin.zuul.ratelimit.config.properties.RateLimitProperties;
import io.focus.mijin.zuul.ratelimit.config.properties.RateLimitProperties.Policy.MatchType;
import io.focus.mijin.zuul.ratelimit.config.properties.RateLimitProperties.Policy.Type;
import io.focus.mijin.zuul.ratelimit.support.RateLimitUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.netflix.zuul.filters.Route;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * Default KeyGenerator implementation.
 *
 * @author wuaj
 */
@RequiredArgsConstructor
public class DefaultRateLimitKeyGenerator implements RateLimitKeyGenerator {

    private final RateLimitProperties properties;

    private final RateLimitUtils rateLimitUtils;

    @Override
    public String key(final HttpServletRequest request, final Route route, final RateLimitProperties.Policy policy) {
        final List<Type> types = policy.getTypes().stream().map(MatchType::getType).collect(Collectors.toList());
        final StringJoiner joiner = new StringJoiner(":");
        joiner.add(properties.getKeyPrefix());
        if (route != null) {
            joiner.add(route.getId());
        }
        if (!types.isEmpty()) {
            if (types.contains(Type.URL) && route != null) {
                joiner.add(route.getPath());
            }
            if (types.contains(Type.IP)) {
                joiner.add(rateLimitUtils.getRemoteIpAddress(request));
            }
            if (types.contains(Type.USER)) {
                joiner.add(rateLimitUtils.getUser(request));
            }
            if (types.contains(Type.PAR)) {
                final List<String> pars = getConfiguredType(policy.getTypes(), Type.PAR);
                pars.forEach(par -> {
                    String value = request.getParameter(par);
                    joiner.add(par + "=" + value);
                });
            }
        }
        return joiner.toString();
    }

    private List<String> getConfiguredType(List<MatchType> types, Type user) {
        return types.stream()
                .filter(matchType -> matchType.getType().equals(user))
                .map(MatchType::getMatcher)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
